const BASE_URL = '/api';

const requestLocks = {}; // 请求锁对象
const requestTimestamps = {}; // 请求时间戳对象
const ignoreLockUrls = ['/uiqa/iqoe', '/uiqa/qyzy', '/uiqa/jvbw', '/uiqa/gzzd',
	'/uiqa/njes', '/njaf/bexh', '/njaf/wmad', '/jvww/rrqp', '/rlky/ntxw', '/zkdu/vueo', '/rlky/lton',
]; //忽略锁的接口

const request = (url, method, data = {}, showToast = true) => {
	console.log('为什么只有h5可以', url);
	const now = Date.now();
	const shouldLock = !ignoreLockUrls.includes(url);
	console.log('【防抖检查】当前 URL：', url);
	console.log('【防抖检查】当前锁：', JSON.stringify(requestLocks));
	console.log('【防抖检查】shouldLock:', shouldLock);
	console.log('【防抖检查】requestLocks[url]:', requestLocks[url]);

	// 添加节流逻辑：3 秒内不能重复请求
	if (shouldLock) {
		const lastTime = requestTimestamps[url] || 0;
		if (now - lastTime < 3000) {
			// uni.showToast({
			// 	title: '操作过于频繁，请稍后再试',
			// 	icon: 'none',
			// });
			console.log('操作过于频繁，请稍后再试');
			return Promise.reject({
				message: '请求频繁，已被节流'
			});
		}
		requestTimestamps[url] = now; // 更新上次请求时间
	}

	if (shouldLock && requestLocks[url]) {
		// uni.showToast({
		// 	title: '请求已在进行中',
		// 	icon: 'none',
		// });
		console.log('请求已在进行中');
		return Promise.reject({
			message: '请求已在进行中'
		});
	}
	// 如果需要锁，且没锁，则设置锁
	if (shouldLock) {
		requestLocks[url] = true;
	}

	if (url != '/uiqa/iqoe' && url != '/rlky/ifMflag' &&
		url != '/uiqa/qyzy' && url != '/uiqa/gzzd'
	) {
		if (uni.getLocale() == 'es') {
			uni.showLoading({
				title: 'Cargando'
			});
		} else {
			uni.showLoading({
				title: 'กำลังโหลด'
			});
		}
	}

	if (url != '/epqt/paas') {
		data.vkpb = uni.getStorageSync('appSsid') || '120';
		data.appSsid = uni.getStorageSync('appSsid') || '120';
		data.znli = 'TH';
		data.blxe = '100';
		data.ignf = '1.0.0';
		data.jvjj = uni.getStorageSync('kjxy') || uni.getStorageSync('userId') || '-1';
		data.kjxy = uni.getStorageSync('kjxy') || uni.getStorageSync('userId');
		data.nkif = uni.getStorageSync('gaid') || '';
		data.sysa = uni.getStorageSync('gaid') || '';
	}

	let hraderValue = {};
	if (url == '/uiqa/gzzd') {
		hraderValue = {
			'Content-Type': 'application/x-www-form-urlencoded',
			'nxbd': uni.getStorageSync('token') || '',
			"client-id": uni.getStorageSync('appSsid') || '120',
		};
	} else if (url == '/epqt/paas') {
		hraderValue = {
			'Content-Type': 'application/json',
			'nxbd': uni.getStorageSync('token') || '',
			"client-id": uni.getStorageSync('appSsid') || '120',
			"blxe": '100',
			"ignf": '1.0.0',
			"nkif": uni.getStorageSync('gaid') || '',
			"sysa": uni.getStorageSync('gaid') || '',
			"jvjj": uni.getStorageSync('kjxy') || uni.getStorageSync('userId') || '-1',
			'kjxy': uni.getStorageSync('kjxy') || uni.getStorageSync('userId'),
			"mulFlag": 1,
		};
	} else if (url == '/uiqa/njes') {
		hraderValue = {
			'Content-Type': 'application/x-www-form-urlencoded',
			'nxbd': uni.getStorageSync('token') || '',
			"client-id": uni.getStorageSync('appSsid') || '120',
			"nkif": uni.getStorageSync('gaid') || '',
			"sysa": uni.getStorageSync('gaid') || '',
		};
	} else {
		hraderValue = {
			'Content-Type': 'application/x-www-form-urlencoded',
			'nxbd': uni.getStorageSync('token') || '',
			"client-id": uni.getStorageSync('appSsid') || '120',
			"blxe": '100',
			"ignf": '1.0.0',
			"nkif": uni.getStorageSync('gaid') || '',
			"sysa": uni.getStorageSync('gaid') || '',
			"jvjj": uni.getStorageSync('kjxy') || uni.getStorageSync('userId') || '-1',
			'kjxy': uni.getStorageSync('kjxy') || uni.getStorageSync('userId'),
			"mulFlag": 1,
		};
	}

	return new Promise((resolve, reject) => {
		let requestUrl = '';
		// #ifdef APP-PLUS
		// requestUrl = "https://test.flashkaching.com/NeoLoan" + url;
		requestUrl = "https://api.neoloanth.com/NeoLoan" + url;
		// #endif
		// #ifdef H5
		requestUrl = BASE_URL + url;
		// #endif

		// console.log('请求地址', requestUrl);
		// console.log('请求参数', data);

		uni.request({
			url: requestUrl,
			method: method,
			data: data,
			header: hraderValue,
			success: (res) => {
				requestLocks[url] = false; // 解锁
				if (url != '/uiqa/iqoe' && url != '/rlky/ifMflag' &&
					url != '/uiqa/qyzy' && url != '/uiqa/gzzd') {
					uni.hideLoading();
				}

				if (res.statusCode === 200) {
					const response = res.data;
					if (response.ggbb === 1000) {
						resolve(response.simh);
					} else if (response.ggbb === -1001 || response.ggbb === -1000) {
						uni.showToast({
							icon: 'none',
							title: response.ytlt,
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/demo1/demo1',
								animationType: 'slide-in-right',
								animationDuration: 200
							});
						}, 1000);
						reject(response);
					} else {
						if (showToast) {
							uni.showToast({
								title: response.ytlt || (uni.getLocale() == 'es' ?
									'Error de solicitud' : 'ข้อผิดพลาดในการร้องขอ'),
								icon: 'none'
							});
						}
						reject(response);
					}
				} else {
					uni.showToast({
						title: uni.getLocale() == 'es' ?
							'Error en la solicitud de red' : 'คำขอเครือข่ายล้มเหลว',
						icon: 'none'
					});
					reject(res);
				}
			},
			fail: (err) => {
				if (shouldLock) requestLocks[url] = false;
				uni.showToast({
					title: uni.getLocale() == 'es' ?
						'Se agotó el tiempo de espera de la solicitud, verifique la red.' :
						'คำขอหมดเวลา โปรดตรวจสอบเครือข่าย',
					icon: 'none'
				});
				console.log('超时的地址——————》》', requestUrl);
				reject(err);
				if (url != '/uiqa/iqoe' && url != '/rlky/ifMflag' &&
					url != '/uiqa/qyzy' && url != '/uiqa/gzzd') {
					uni.hideLoading();
				}
			},
			complete: () => {
				if (shouldLock) requestLocks[url] = false;
			}
		});
	});
};

export default request;